<!--  -->
<template>
  <div class="maxbg">
    <transition name="fade">
      <div class="pageBody g-bg crouse">
        <div class="dt-top pay-head">
          <div class="back" @click="goback">返回</div>
          <div class="tl">订单详情</div>
          <div class="down-btn" @click="linkCourse">下载APP</div>
        </div>
        <div class="pay-main">
          <div class="order-time">剩余时间{{ time }}自动关闭</div>
          <div class="pay-card">
            <div class="cd-infor">
              <div class="cd-img">
                <img :src="orderInfor.specificationCover" />
              </div>
              <div class="cd-tl">{{ orderInfor.specificationName }}</div>
              <div class="cd-money">
                {{ orderInfor.amountPayable / 1000 }}芝士
              </div>
            </div>
            <div class="course-infor">
              <div class="course-money c-box">
                <div>商品金额</div>
                <div>
                  {{ (orderInfor.amountActually / 1000).toFixed(2) }}芝士
                </div>
              </div>
              <div class="course-time c-box" v-if="orderInfor.memberDiscount">
                <div>会员折扣</div>
                <div class="discount">{{ orderInfor.memberDiscount }}折</div>
              </div>

              <div class="course-time c-box" v-if="orderInfor.expiryDateText">
                <div>内容有效期</div>
                <div>{{ orderInfor.expiryDateText }}</div>
              </div>
            </div>
            <div class="course-service"></div>
          </div>
          <div class="pay-infor">
            <div class="pay-box">
              <div
                class="pay-gp wechat"
                :class="[payType == 'wechat' ? 'on' : '']"
                @click="pay('wechat')"
              >
                微信支付
              </div>
              <div
                class="pay-gp alipay"
                :class="[payType == 'alipay' ? 'on' : '']"
                @click="pay('alipay')"
              >
                支付宝支付
              </div>
            </div>
          </div>
        </div>
        <div class="vip-box" v-if="!isUserInfoComplete">
          <div class="vip-inf-img"></div>
          <div class="vip-tl">赠送7天会员，享88折优惠！</div>
          <div class="vip-btn" @click="gotoInforPage">立即完善</div>
        </div>
        <div class="order-bt-gp">
          <div>
            <span class="tip">实付金额：</span
            ><span class="money"
              >¥{{ (orderInfor.amountActually / 1000).toFixed(2) }}</span
            >
          </div>
          <div class="buy-btn" @click="getCommodity">立即购买</div>
        </div>
      </div>
    </transition>
  </div>
  <div class="mask" v-if="paySuccess">
    <div class="modal">
      <div class="moadl-tl">提示</div>
      <div class="modal-tx">支付成功</div>
      <div class="modal-btn" @click="gotoBack">知道了</div>
    </div>
  </div>
  <div class="mask" v-if="isWxAlipay" @click="isWxAlipay = false">
    <div class="gotoWeb"></div>
  </div>
</template>
  
  <script>
import { os } from "@/utils/base.js";
import wx from "weixin-js-sdk";
export default {
  data() {
    return {
      vipOrderInfo: {
        amountActually: 0,
      },
      payType: "wechat",
      time: null,
      tabIdx: 1,
      isSuccess: false,
      orderInfor: {
        amountActually: 0,
        amountPayable: 0,
      },
      balance: 0,
      isPay: true,
      specificationId: null,
      isModal: false,
      courseType: null,
      checkOrderState: null,
      orderState: null,
      paySuccess: false,
      isWxAlipay: false,
      isUserInfoComplete: false,
    };
  },
  components: {},
  created() {
    this.init();
  },
  mounted() {
    this.getOrderState();
    this.getUserCompleteInfo();
  },

  methods: {
    getUserCompleteInfo() {
      this.$http
        .getUserCompleteInfo()
        .then(async (res) => {
          if (res.flag === 0) {
            this.isUserInfoComplete = res.data == 0 ? false : true;
          }
        })
        .catch((err) => {
          // this.$Message.error(err.response.data.message);
        });
    },
    gotoInforPage() {
      const userInfo = {
        idx: 4,
      };
      localStorage.setItem("userInfo", JSON.stringify(userInfo));
      this.$router.push({
        path: "/myinformation",
      });
    },
    gotoBack() {
      const specificationId = this.$route.query.specificationId;
      const courseId = this.$route.query.courseId;
      const code = this.$route.query.invitationCode
        ? this.$route.query.invitationCode
        : "";
      const actionType = this.$route.query.actionType;
      // this.$router.push({ path: "/", query: { courseId: courseId } });
      window.location.href =
        "/h5/?id=" +
        courseId +
        "&actionType=" +
        actionType +
        "&invitationCode=" +
        code;
    },
    goback() {
      this.$router.go(-1);
    },
    pay(name) {
      this.payType = name;
    },
    getOrderState() {
      this.specificationId = this.$route.query.specificationId;
      const orderId = this.$route.query.orderId;
      if (orderId) {
        this.orderId = orderId;
        this.getCommodityState();
      } else {
        this.getOrder();
      }
    },
    getOrder() {
      const parames = {
        quantity: 1,
        specificationId: this.specificationId,
        agentCode: this.$route.query.invitationCode
          ? this.$route.query.invitationCode
          : null,
      };
      this.$http
        .placeOrder(parames)
        .then((res) => {
          if (res.flag == 0) {
            this.orderInfor = res.data;
            this.orderId = res.data.id;
            this.countdown = res.data.countdown;
            // this.getCommodity();
            const time = setInterval(() => {
              if (this.countdown > 0) {
                this.countdown--;
                this.time = this.shiftTimeStamp(this.countdown);
              } else {
                clearInterval(time);
              }
            }, 1000);
          }
        })
        .catch((err) => {
          // ElMessage.error(err.response.data.message);
        });
    },
    getCommodity() {
      //支付方式 1-余额 2-微信 3-支付宝 4-APPLE 5-人工调整
      const orderId = this.$route.query.orderId;
      const obj = {
        payway: this.payType == "wechat" ? 2 : 3,
        orderId: this.orderId,
        payType: 2,
      };
      if (os.weixin) {
        obj.payType = 3;
        obj.wxJsapiCode = sessionStorage.getItem("wxCode");
      }
      if (this.payType == "alipay") {
        obj.rtnUrl = window.location.href + "&orderId=" + this.orderId;
      } else {
        obj.wxH5Type = "充值余额";
      }
      this.$http
        .getCommodity(obj)
        .then((res) => {
          if (res.flag == 0) {
            if (this.payType == "wechat") {
              const url = encodeURIComponent(
                window.location.href + "&orderId=" + this.orderId
              );
              if (os.weixin) {
                this.initWXPay(res.data.wechatpayBody);
              } else {
                window.location.href =
                  res.data.wechatpayBody.h5_url + "&redirect_url=" + url;
              }
            } else {
              if (os.weixin) {
                this.isWxAlipay = true;
              } else {
                window.location.href =
                  "https://openapi.alipay.com/gateway.do?" + res.data.body;
              }
            }
            // this.getCommodityState();
          }
        })
        .catch((err) => {
          console.log(err.response.data.message);
        });
    },
    getCommodityState() {
      this.$http
        .getCommodityState(this.orderId)
        .then((res) => {
          if (res.flag == 0) {
            if ((res.data & 0x2) != 0) {
              this.paySuccess = true;
            } else {
              this.getOrder();
            }
          }
        })
        .catch((err) => {
          console.log(err.response.data.message);
        });
    },
    checkStatus() {
      this.specificationId = this.$route.query.specificationId;
      this.courseId = this.$route.query.courseId;
      this.courseType = this.$route.query.courseType;
      this.$http
        .getCourseDetail(this.courseId)
        .then((res) => {
          payOrder;
          if (res.flag == 0) {
            if (res.data.accessAuth != 1) {
              this.isPay = true;
              this.courseId = res.data.id;
              this.getOrder();
            } else {
              this.isPay = false;
              setTimeout(() => {
                this.$router.push({
                  path: "/",
                  query: {
                    courseId: res.data.id,
                  },
                });
              }, 2000);
            }
          }
        })
        .catch((err) => {
          // ElMessage.error(err.response.data.message);
        });
    },
    shiftTimeStamp(time) {
      // time /= 1000; 如果传进来的是 毫秒 形式，则在这里除1000将其转为 秒 形式

      let hour = Number.parseInt(time / 3600); // 获取总的小时
      let min = Number.parseInt((time - hour * 3600) / 60); // 获取总分钟
      let sec = time - hour * 3600 - min * 60; // 减去总 分 后剩余的分秒数
      if (!hour) {
        // 小时为0时
        return this.f_m_dispose(min, sec);
      } else {
        // 小时大于0的处理
        if (!min) {
          // 分为0时
          // 如果秒也小于10，则返回 例1:00:07
          return sec < 10
            ? hour + ":" + "00" + ":0" + sec
            : hour + ":" + "00" + ":" + sec;
        } else {
          // 有分钟时的处理
          return hour + ":" + this.f_m_dispose(min, sec); // 返回总小时加上处理好的分秒数
        }
      }
    },
    f_m_dispose(min, sec) {
      // 分秒处理函数
      if (min < 10 && sec < 10) {
        return "0" + min + ":" + "0" + sec; // 如果分和秒都小于10，则前面都加入0
      } else if (min < 10 && sec >= 10) {
        return "0" + min + ":" + sec; // 如果分小于10，秒大于10，则给分前面加0
      } else if (min >= 10 && sec < 10) {
        return min + ":" + "0" + sec; // 如果分大于10，秒小于10，则给秒前面加0
      } else {
        return min + ":" + sec; // 如果分秒都大于10，则直接return
      }
    },
    init() {
      const s = document.createElement("script");
      s.type = "text/javascript";
      s.src = "//web.cdn.openinstall.io/openinstall.js";
      s.addEventListener(
        "load",
        () => {
          var data = OpenInstall.parseUrlParams();
          new OpenInstall(
            {
              appKey: "zpyiil", //appkey参数配置,需要自行替换对应的appkey
              onready: function () {
                var m = this;
                /*在app已安装的情况尝试拉起app*/
                m.schemeWakeup({
                  data: data,
                  channelCode: "test-channelcode",
                });
                window.wakeupOrInstall = function () {
                  this.rnum = this.rnum + 1;
                  m.wakeupOrInstall({
                    data: data,
                    channelCode: "test-channelcode",
                  });
                };
              },
            },
            data
          );
        },
        false
      );
      document.head.appendChild(s);
    },
    linkCourse() {
      // alert('下载课程')
      // console.log(1212)
      window.wakeupOrInstall(); //此方法为scheme、Universal Link唤醒以及引导下载的作用（必须调用且不可额外自行跳转下载）
      return false;
    },
    initWXPay(config) {
      var that = this;
      wx.config({
        debug: false,
        appId: config.appId,
        timestamp: config.timeStamp,
        nonceStr: config.nonceStr,
        signature: config.signature,
        jsApiList: ["chooseWXPay"],
      });

      wx.ready(() => {
        // 微信支付配置完成后，调用支付函数
        wx.chooseWXPay({
          timestamp: config.timeStamp,
          nonceStr: config.nonceStr,
          package: config.packageValue,
          signType: config.signType,
          paySign: config.paySign,
          success: function (res) {
            // 支付成功的回调
            that.paySuccess =true;
          },
          fail: function (res) {
            // 支付失败的回调
          },
          complete: (res) => {
            if (res.errMsg == "chooseWXPay:ok") {
              // 回调函数内容
              that.paySuccess =true;
            }
          },
        });
      });
    },
  },
};
</script>
  
  <style lang='scss' scoped>
</style>
  